<?php

namespace App\Trip\Plane;

use App\Jobs\Plane\Query\ProcessMixedTicketQuery;
use App\Trip\Enums\Plane\PlaneProviders;
use App\Trip\Plane\Interfaces\Result\Abstracts\AbstractFlightQueryResult;
use App\Trip\Plane\Requests\TicketQueryRequest;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;

/**
 * 航班多供应商混合查询
 */
class MixedPlaneQueryResult extends AbstractFlightQueryResult
{
    private TicketQueryRequest $request;
    private Collection         $lists;

    public function __construct(TicketQueryRequest $request)
    {
        $this->request = $request;
    }


    public function getLists(): Collection
    {
        // 以 qunar 为主
        $main_provider = PlaneProviders::QUNAR;
        $service       = $main_provider->getPlaneQueryStrategy();
        // 这里使用队里将结果压入 redis
        $other_providers = [
            PlaneProviders::BOOK51,
        ];
        // 队列处理
        /**
         * @var PlaneProviders $provider
         */
        foreach ($other_providers as $provider) {
            ProcessMixedTicketQuery::dispatch($provider->value, $this->request->getRequestParamKey());
        }

        // 查询
        $res         = $service->ticket_query($this->request);
        $this->lists = $res->getLists();

        // 查询 是否有缓存的结果
        foreach ($other_providers as $provider) {
            $cache_key = "{$this->request->getRequestParamKey()}:{$provider->value}";
            if (Cache::has($cache_key)) {
                $cache       = Cache::get($cache_key);
                $this->lists = $this->lists->merge($cache);
            }
        }
        // 航班去重,并取价格低的
        $this->lists = $this->lists->sortBy(function ($flight) {
            return $flight['flight_price'];
        })->unique(function ($flight) {
            return $flight['flight_no'];
        });
        return $this->lists;
    }


    public function getCount(): int
    {
        return $this->lists->count();
    }
}